{% extends 'layout/manage.html' %}
{% load static %}

{% block css %}
    <!-- 引入editor.md css -->
    <link rel="stylesheet" href="{% static 'plugin/editor.md/css/editormd.min.css' %}">
    <!-- 引入bootstrap-datepicker css -->
    <link rel="stylesheet" href="{% static 'plugin/bootstrap-datepicker/css/bootstrap-datepicker.min.css' %}">
    <!-- 引入bootstrap-select css -->
    <link rel="stylesheet" href="{% static 'plugin/bootstrap-select/css/bootstrap-select.min.css' %}">

    <style>
        .comment-area .item {
            margin-top: 20px;
        }

        .comment-area .left-avatar {
            float: left;
            margin-right: 10px;
            display: inline-block;
            width: 30px;
            height: 30px;
            background-color: #304659;
            color: white;
            text-align: center;
            line-height: 30px;
            border-radius: 50%;
        }

        .comment-area .right-info {
            padding-left: 35px;
        }

        .comment-area .right-info .desc .msg {
            display: inline-block;
            padding-right: 20px;
            color: #8c8c8c;
        }

        .comment-area .child {
            padding-left: 55px;
        }

        .comment-area .error-msg {
            color: red;
        }

        .comment-area .reply-user {
            display: inline-block;
            background-color: #dddddd;
            color: black;
            padding: 6px 8px;
            margin-left: 20px;
            border-radius: 8px;
            cursor: pointer;
        }

        .editormd-fullscreen {
            z-index: 1001;
        }
    </style>

{% endblock %}

{% block content %}
    <div class="container-fluid clearfix" style="padding: 20px 0px;">

        <div class="col-sm-7">
            <div class="panel panel-default">
                <div class="panel-heading">
                    <div>
                        <i class="fa fa-edit"></i> 更新问题
                    </div>
                </div>

                <div class="panel-body">
                    <form id="editForm" class="form-horizontal">
                        {% csrf_token %}
                        <!-- 问题类型 -->
                        <div class="form-group">
                            <label for="{{ form.issues_type.id_for_label }}"
                                   class="col-sm-2 control-label">{{ form.issues_type.label }}</label>
                            <div class="col-sm-10">
                                <div>
                                    {{ form.issues_type }}
                                </div>
                                <span class="error-msg">{{ form.issues_type.errors.0 }}</span>
                            </div>
                        </div>
                        <!-- 主题 -->
                        <div class="form-group">
                            <label for="{{ form.subject.id_for_label }}"
                                   class="col-sm-2 control-label">{{ form.subject.label }}</label>
                            <div class="col-sm-10">
                                <div>
                                    {{ form.subject }}
                                </div>
                                <span class="error-msg">{{ form.subject.errors.0 }}</span>
                            </div>
                        </div>
                        <!-- 模块 -->
                        <div class="form-group">
                            <label for="{{ form.module.id_for_label }}"
                                   class="col-sm-2 control-label">{{ form.module.label }}</label>
                            <div class="col-sm-10">
                                <div>
                                    {{ form.module }}
                                </div>
                                <span class="error-msg">{{ form.module.errors.0 }}</span>
                            </div>
                        </div>
                        <!-- 描述 -->
                        <div class="form-group">
                            <label for="{{ form.desc.id_for_label }}"
                                   class="col-sm-2 control-label">{{ form.desc.label }}</label>
                            <div class="col-sm-10">
                                <div id="editor">
                                    {{ form.desc }}
                                </div>
                                <span class="error-msg">{{ form.desc.errors.0 }}</span>
                            </div>
                        </div>
                        <div class="form-group clearfix">
                            <!--左边-->
                            <div class="col-md-6 pd-0">
                                <label for="{{ form.status.id_for_label }}"
                                       class="col-sm-2 control-label">{{ form.status.label }}</label>
                                <div class="col-md-8 ">
                                    <div>
                                        {{ form.status }}
                                    </div>
                                    <span class="error-msg">{{ form.status.errors.0 }}</span>
                                </div>
                            </div>
                            <!--右边-->
                            <div class="col-md-6 pd-0">
                                <label for="{{ form.priority.id_for_label }}"
                                       class="col-sm-2 control-label">{{ form.priority.label }}</label>
                                <div class="col-md-8 ">
                                    <div>
                                        {{ form.priority }}
                                    </div>
                                    <span class="error-msg">{{ form.priority.errors.0 }}</span>
                                </div>
                            </div>
                        </div>
                        <div class="form-group clearfix">
                            <!--左边-->
                            <div class="col-md-6 pd-0">
                                <label for="{{ form.assign.id_for_label }}"
                                       class="col-sm-2 control-label">{{ form.assign.label }}</label>
                                <div class="col-md-8 ">
                                    {{ form.assign }}
                                    <span class="error-msg">{{ form.assign.errors.0 }}</span>
                                </div>
                            </div>
                            <!--右边-->
                            <div class="col-md-6 pd-0">
                                <label for="{{ form.attention.id_for_label }}"
                                       class="col-sm-2 control-label">{{ form.attention.label }}</label>
                                <div class="col-md-8 ">
                                    {{ form.attention }}
                                    <span class="error-msg">{{ form.attention.errors.0 }}</span>
                                </div>
                            </div>
                        </div>
                        <div class="form-group clearfix">
                            <!--左边-->
                            <div class="col-md-6 pd-0">
                                <label for="{{ form.start_date.id_for_label }}"
                                       class="col-sm-2 control-label">{{ form.start_date.label }}</label>
                                <div class="col-md-8">
                                    <div class="input-group">
                                        <span class="input-group-addon" id="sizing-addon">
                                            <i class="fa fa-calendar" aria-hidden="true"></i>
                                        </span>
                                        {{ form.start_date }}
                                    </div>
                                    <span class="error-msg">{{ form.start_date.errors.0 }}</span>
                                </div>
                            </div>
                            <!--右边-->
                            <div class="col-md-6 pd-0">
                                <label for="{{ form.end_date.id_for_label }}"
                                       class="col-sm-2 control-label">{{ form.end_date.label }}</label>
                                <div class="col-md-8">
                                    <div class="input-group">
                                        <span class="input-group-addon" id="sizing-addon">
                                            <i class="fa fa-calendar" aria-hidden="true"></i>
                                        </span>
                                        {{ form.end_date }}
                                    </div>
                                    <span class="error-msg">{{ form.end_date.errors.0 }}</span>
                                </div>
                            </div>
                        </div>
                        <div class="form-group clearfix">
                            <!--左边-->
                            <div class="col-md-6 pd-0">
                                <label for="{{ form.mode.id_for_label }}"
                                       class="col-sm-2 control-label">{{ form.mode.label }}</label>
                                <div class="col-md-8 ">
                                    <div>
                                        {{ form.mode }}
                                    </div>
                                    <span class="error-msg">{{ form.mode.errors.0 }}</span>
                                </div>
                            </div>
                            <!--右边-->
                            <div class="col-md-6 pd-0">
                                <label for="{{ form.parent.id_for_label }}"
                                       class="col-sm-2 control-label">{{ form.parent.label }}</label>
                                <div class="col-md-8 ">
                                    <div>
                                        {{ form.parent }}
                                    </div>
                                    <span class="error-msg">{{ form.parent.errors.0 }}</span>
                                </div>
                            </div>
                        </div>

                    </form>
                </div>

            </div>
        </div>

        <div class="col-sm-5">
            <div class="panel panel-default">
                <div class="panel-heading">
                    <i class="fa fa-search"></i> 操作记录
                </div>
                <div class="panel-body comment-area">

                    <div class="comment-list">

                    </div>

                    <hr>

                    <div class="comment-text" id="commentText">
                        <div class="form-group">
                            <textarea id="content" rows="6" class="form-control" placeholder="回复内容"></textarea>
                            <span class="error-msg"></span>
                        </div>
                        <input type="button" class="btn btn-primary" id="btnSubmit" value="提 交">
                        <div class="reply-user hide" id="replyUser">
                            回复 <span></span>
                            <i class="fa fa-times-circle" aria-hidden="true" style=""></i>
                        </div>
                    </div>

                </div>
            </div>
        </div>

    </div>

    <!-- 回复评论的模板 -->
    <div class="hide" id="recordTemplate">
        <div class="item clearfix">
            <!--头像-->
            <div class="left-avatar"></div>
            <!--右边内容-->
            <div class="right-info">
                <!--内容-->
                <pre></pre>
                <!--一些描述信息-->
                <div class="desc">
                    <div class="msg">
                        <i class="fa fa-bullhorn" aria-hidden="true"></i>
                        <span class="type"></span>
                    </div>
                    <div class="msg">
                        <i class="fa fa-user-o" aria-hidden="true"></i>
                        <span class="user"></span>
                    </div>
                    <div class="msg">
                        <i class="fa fa-clock-o" aria-hidden="true"></i>
                        <span class="date"></span>
                    </div>
                    <a href="#commentText" class="reply">
                        <i class="fa fa-commenting-o" aria-hidden="true"></i> 回复
                    </a>
                </div>
            </div>
            <!--子回复-->
            <div class="child"></div>
        </div>
    </div>

{% endblock %}

{% block js %}
    <script src="{% static 'plugin/editor.md/editormd.min.js' %}"></script>
    <script src="{% static 'plugin/bootstrap-datepicker/js/bootstrap-datepicker.min.js' %}"></script>
    <script src="{% static 'plugin/bootstrap-datepicker/locales/bootstrap-datepicker.zh-CN.min.js' %}"></script>
    <script src="{% static 'plugin/bootstrap-select/js/bootstrap-select.min.js' %}"></script>
    <script src="{% static 'plugin/bootstrap-select/js/i18n/defaults-zh_CN.js' %}"></script>

    <script>
        var WIKI_UPLOAD_URL = "{% url 'web:wiki_upload' project_id=request.tracer.project.id %}";
        var ISSUES_RECORD_API = "{% url 'web:issues_record' project_id=request.tracer.project.id issues_id=issues_obj.id %}";
        var ISSUES_CHANGE_API = "{% url 'web:issues_change' project_id=request.tracer.project.id issues_id=issues_obj.id %}";
        var EDITOR;

        $(function () {
            // 初始化组件
            initDatePicker();
            // 初始化md
            initEditorMd();
            // 初始化讨论信息
            initIssuesRecord();
            // 点击回复 显示被回复的人
            bindReply();
            // 取消回复
            bindCancelReplyUser();
            // 提交回复内容
            bindSubmit();
            // 更新问题
            bindChangeIssues();
        });

        function initEditorMd() {
            // 定义全局变量
            EDITOR = editormd('editor', {
                placeholder: '请输入内容',
                height: 300,
                path: '{% static "plugin/editor.md/lib/" %}',  // 指定依赖文件地址
                imageUpload: true,  // 支持本地上传
                imageFormats: ['jpg', 'jpeg', 'png', 'gif'], // 支持上传的图片
                imageUploadURL: WIKI_UPLOAD_URL,  // 上传到的地址(使用wiki的接口)
                onload: function () {
                    this.previewing();  // markdown在详情页默认以预览状态展示，而不是编辑状态
                },
                // 自定义显示Markdown编辑器上面的菜单
                toolbarIcons: function () {
                    return ['bold', 'del', 'hr', 'italic', 'quote', '|', 'image', 'preview', 'watch', 'fullscreen',
                        '||', 'save'] // 自定义了一个Markdown的菜单项
                },
                toolbarCustomIcons: {
                    save: '<input type="button" value="保 存" class="btn btn-success btn-sm" onclick="saveDesc();">'
                },
                toolbarAutoFixed: false,  // 往下滚动时，不停在顶部，而是直接滚过去
            })
        }

        function initDatePicker() {
            $('#id_start_date,#id_end_date').datepicker({
                format: 'yyyy-mm-dd',
                startDate: '0',
                language: 'zh-CN',
                autoclose: true,
            })
        }

        // 问题评论初始化
        function initIssuesRecord() {
            $.ajax({
                url: ISSUES_RECORD_API,
                type: 'GET',
                dataType: 'JSON',
                success: function (res) {
                    if (res.status) {
                        //
                        $.each(res.data, function (index, item) {
                            createRecordNode(item);
                        })
                    } else {
                        console.log('err')
                    }
                }
            })
        }

        // 创建一个问题评论元素节点
        function createRecordNode(nodeDict) {
            var $item = $('#recordTemplate').find('.item').clone();
            $item.find('.left-avatar').html(nodeDict.creator[0].toUpperCase());
            $item.find('pre').html(nodeDict.content);
            $item.find('.user').html(nodeDict.creator);
            $item.find('.type').html(nodeDict.reply_type_text);
            $item.find('.date').html(nodeDict.datetime);

            $item.attr({id: nodeDict.id, username: nodeDict.creator});

            if (nodeDict.parent_id) {
                // 挂在父元素
                $('#' + nodeDict.parent_id).children('.child').append($item);
            } else {
                // 根节点
                $('.comment-list').append($item);
            }

        }

        // 回复某个问题
        function bindReply() {
            $('.comment-list').on('click', '.reply', function () {
                var $item = $(this).parent().parent().parent();
                var id = $item.attr('id');
                var username = $item.attr('username');
                $('#replyUser').removeClass('hide').attr('parent-id', id).children('span').text(username);
            })
        }

        // 取消回复，即点击叉叉，取消回复某个问题
        function bindCancelReplyUser() {
            $('#replyUser').click(function () {
                $(this).addClass('hide').removeAttr('parent-id').children('span').text('');
            })
        }

        // 评论
        function bindSubmit() {
            $('#btnSubmit').click(function () {
                // 清空错误信息
                $('#commentText .error-msg').text('');
                $.ajax({
                    url: ISSUES_RECORD_API,
                    type: 'POST',
                    dataType: 'JSON',
                    data: {content: $('#content').val(), reply: $('#replyUser').attr('parent-id')},
                    success: function (res) {
                        if (res.status) {
                            createRecordNode(res.data);
                            // 清空输入框
                            $('#content').val('');
                            $('#replyUser').addClass('hide').removeAttr('parent-id').children('span').text('');
                        } else {
                            $.each(req.error, function (k, v) {
                                $('#content').next('.error-msg').text(v[0]);
                            })
                        }
                    }
                })
            });
        }

        // 问题更新事件
        function bindChangeIssues() {
            $('#editForm').find('.form-control').change(function () {
                // 内容改变
                var postDict = {name: $(this).attr('name'), value: $(this).val()};
                poseAjaxData(postDict);
            })
        }

        // 保存markdown的文本
        function saveDesc() {
            var postDict = {name: 'desc', value: EDITOR.getValue()};
            poseAjaxData(postDict);
        }
        function poseAjaxData(postDict) {
            $('#id_' + postDict.name).parent().next('.error-msg').text('');
            $.ajax({
                url: ISSUES_CHANGE_API,
                header: {
                    'Content-Type': 'application/json;charset=utf-8'
                },
                type: 'POST',
                data: JSON.stringify(postDict),
                dataType: 'JSON',
                success: function (res) {
                    console.log(res)
                    if(res.status){
                        createRecordNode(res.data);
                    } else {
                        $('#id_' + postDict.name).parent().next('.error-msg').text(res.error);
                    }
                }
            })
        }
    </script>
{% endblock %}